package com.cavedroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

public class DonationsText extends TextView {
	
	private Context context;
	
	private double total;
	private JSONArray table = null;
	
	private String text;
	
	private static final String DONATIONS_TABLE_PREF = "donationsTable";
	
	public DonationsText(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		initDonations();
	}
	
	public DonationsText(Context context) {
		super(context);
		this.context = context;
		initDonations();
	}
	
	private void initDonations() {
		getTable();
		setClickable(true);
		setMovementMethod(LinkMovementMethod.getInstance());
		text = getText().toString();
		newDonator();
	}
	
	private void getTable() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		String jsonString = prefs.getString(DONATIONS_TABLE_PREF, "");
		JSONObject jsonObj;
		if (jsonString != "") {
			try {
				jsonObj = new JSONObject(jsonString);
				total = jsonObj.getDouble("total");
				table = jsonObj.getJSONArray("table");
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void loadDonators(Context context, String url){
		new DonationsDownloader(context, url);
	}
	
	public void newDonator() {
		if (table == null) {
			getTable();
		}
		if (table != null) {
			JSONObject donator = getDonator();
			if (donator != null) {
				String displayText = text.replaceAll("%donator%", donator.optString("donation_linktext"));
				String site = donator.optString("donation_website");
				if (site == "") {
					site = CaveViewActivity.DONATION_URL;
				}
				displayText = displayText.replaceAll("%website%", site);
				setText(Html.fromHtml(displayText));
			} else {
				setText("");
			}
		} else {
			setText("");
		}
    }
	
	//Gets a donator randomly by weight
	public JSONObject getDonator() {
		double randomWeight = total*Math.random();
		int i = 0;
		JSONObject donation = null;
		try {
			while (randomWeight > 0) {
				donation = table.getJSONObject(i);
				randomWeight -= donation.getDouble("donation_weighting");
				i++;
			}
			//Log.d("Cavedroid", donation.getString("donation_linktext"));
		} catch (JSONException e) {
			Log.d("Cavedroid", "" + i + " " + randomWeight);
			e.printStackTrace();
		}
		return donation;
	}
	
	private static class DonationsDownloader extends Thread {
		
		private URL url;
		
		Context context;
		
		private static final String ENCODING = "UTF-8";
		
		public DonationsDownloader(Context context, String url) {
			super();
			
			try {
				this.url = new URL(url);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			
			this.context = context;
			start();
		}
		
		@Override 
		public void run() {
			try {
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setDoInput(true);
				conn.setDoOutput(true);
				conn.connect();
				String outputString = toString(conn.getInputStream());
				
				//Add to preferences
				SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
	        	Editor prefsEditor = prefs.edit();

	        	prefsEditor.putString(DONATIONS_TABLE_PREF, outputString);
	        	
	        	Log.d("Cavedroid", outputString);
	        	
	        	prefsEditor.commit();
			} catch (IOException e) {
				//Ignore the error as it most likely just means a lack of internet connection
				e.printStackTrace();
			}
		}
		
		private String toString(InputStream inputStream) throws IOException {
			StringBuilder outputBuilder = new StringBuilder();
		    String string;
		    if (inputStream != null) {
		    	BufferedReader reader = new BufferedReader(new InputStreamReader(
		              inputStream, ENCODING));
		    	while (null != (string = reader.readLine())) {
		    		outputBuilder.append(string).append('\n');
		    	}	
		    }
		    return outputBuilder.toString();
		  }

	}

}
